package com.yupi.oj.controller;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.yupi.oj.annotation.AuthCheck;
import com.yupi.oj.common.BaseResponse;
import com.yupi.oj.common.DeleteRequest;
import com.yupi.oj.common.ErrorCode;
import com.yupi.oj.common.ResultUtils;
import com.yupi.oj.constant.UserConstant;
import com.yupi.oj.exception.BusinessException;
import com.yupi.oj.exception.ThrowUtils;
import com.yupi.oj.model.dto.question.*;
import com.yupi.oj.model.entity.Question;
import com.yupi.oj.model.entity.QuestionTag;
import com.yupi.oj.model.entity.Tag;
import com.yupi.oj.model.entity.User;
import com.yupi.oj.model.vo.MakeQuestionRankVO;
import com.yupi.oj.model.vo.QuestionVO;
import com.yupi.oj.service.QuestionService;
import com.yupi.oj.service.QuestionTagService;
import com.yupi.oj.service.TagService;
import com.yupi.oj.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.transaction.support.TransactionTemplate;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 题目接口
 *

 */
@RestController
@RequestMapping("/question")
@Slf4j
public class QuestionController {

    @Resource
    private QuestionService questionService;

    @Resource
    private UserService userService;
    @Resource
    private QuestionTagService questionTagService;
    @Resource
    private TransactionTemplate transactionTemplate;
    @Resource
    private TagService tagService;
    // region 增删改查

    /**
     * 创建
     *
     * @param questionAddRequest
     * @param request
     * @return
     */
    @PostMapping("/add")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    public BaseResponse<Long> addQuestion(@RequestBody QuestionAddRequest questionAddRequest, HttpServletRequest request) {
        if (questionAddRequest == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        Question question = new Question();
        BeanUtils.copyProperties(questionAddRequest, question);
        List<JudgeCase> judgeCase = questionAddRequest.getJudgeCase();
        if(judgeCase!=null){
            question.setJudgeCase(JSONUtil.toJsonStr(judgeCase));
        }
        JudgeConfig judgeConfig = questionAddRequest.getJudgeConfig();
        if(judgeConfig!=null){
            question.setJudgeConfig(JSONUtil.toJsonStr(judgeConfig));
        }
        List<Integer> tagIds = questionAddRequest.getTagIds();
        // 查询tagName
        QueryWrapper<Tag> tagQueryWrapper = new QueryWrapper<>();
        tagQueryWrapper.select("tagName")
                .in("id", tagIds);
        List<Tag> tagList = tagService.list(tagQueryWrapper);
        ThrowUtils.throwIf(CollUtil.isEmpty(tagList), ErrorCode.NOT_FOUND_ERROR);
        List<String> tagNameList = tagList.stream()
                .map(Tag::getTagName)
                .collect(Collectors.toList());
        if(CollUtil.isNotEmpty( tagNameList)){
            question.setTags(JSONUtil.toJsonStr(tagNameList));
        }
        questionService.validQuestion(question, true);
        User loginUser = userService.getLoginUser(request);
        question.setUserId(loginUser.getId());
        question.setFavourNum(0);
        question.setThumbNum(0);
        final long[] newQuestionId = {0L};
        transactionTemplate.execute(
                transactionStatus -> {
                    boolean result = questionService.save(question);
                    ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR);
                    newQuestionId[0] = question.getId();
                    // 添加question_tag表
                    List<QuestionTag> questionTagList = new ArrayList<>();
                    if(CollUtil.isNotEmpty(tagIds)){
                        tagIds.forEach(tag -> {
                            QuestionTag questionTag = new QuestionTag();
                            questionTag.setQuestionId(newQuestionId[0]);
                            questionTag.setTagId(tag);
                            questionTagList.add(questionTag);
                        });
                    }
                    if(CollUtil.isNotEmpty(questionTagList)){
                        boolean b = questionTagService.saveBatch(questionTagList);
                        ThrowUtils.throwIf(!b, ErrorCode.OPERATION_ERROR);
                    }
                    return newQuestionId[0];
                }
        );
        return ResultUtils.success(newQuestionId[0]);
    }

    /**
     * 删除
     *
     * @param deleteRequest
     * @param request
     * @return
     */
    @PostMapping("/delete")
    public BaseResponse<Boolean> deleteQuestion(@RequestBody DeleteRequest deleteRequest, HttpServletRequest request) {
        if (deleteRequest == null || deleteRequest.getId() <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        User user = userService.getLoginUser(request);
        long id = deleteRequest.getId();
        // 判断是否存在
        Question oldQuestion = questionService.getById(id);
        ThrowUtils.throwIf(oldQuestion == null, ErrorCode.NOT_FOUND_ERROR);
        // 仅本人或管理员可删除
        if (!oldQuestion.getUserId().equals(user.getId()) && !userService.isAdmin(request)) {
            throw new BusinessException(ErrorCode.NO_AUTH_ERROR);
        }
        final boolean[] b = new boolean[1];
        transactionTemplate.execute(executeTransaction -> {
             b[0] = questionService.removeById(id);
            ThrowUtils.throwIf(!b[0], ErrorCode.OPERATION_ERROR);
            // 删除question_tag表
            boolean remove = questionTagService.remove(new QueryWrapper<QuestionTag>().eq("questionId", id));
            ThrowUtils.throwIf(!remove, ErrorCode.OPERATION_ERROR);
            return b[0];
        });
        return ResultUtils.success(b[0]);
    }

    /**
     * 更新（仅管理员）
     *
     * @param questionUpdateRequest
     * @return
     */
    @PostMapping("/update")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    public BaseResponse<Boolean> updateQuestion(@RequestBody QuestionUpdateRequest questionUpdateRequest) {
        if (questionUpdateRequest == null || questionUpdateRequest.getId() <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        Question question = new Question();
        BeanUtils.copyProperties(questionUpdateRequest, question);
        List<String> tags = questionUpdateRequest.getTags();
        if (tags != null) {
            question.setTags(JSONUtil.toJsonStr(tags));
        }
        JudgeConfig judgeConfig = questionUpdateRequest.getJudgeConfig();
        if(judgeConfig!=null){
            question.setJudgeConfig(JSONUtil.toJsonStr(judgeConfig));
        }
        List<JudgeCase> judgeCase = questionUpdateRequest.getJudgeCase();
        if(judgeCase!=null){
            question.setJudgeCase(JSONUtil.toJsonStr(judgeCase));
        }
        // 参数校验
        questionService.validQuestion(question, false);
        long id = questionUpdateRequest.getId();
        // 判断是否存在
        Question oldQuestion = questionService.getById(id);
        ThrowUtils.throwIf(oldQuestion == null, ErrorCode.NOT_FOUND_ERROR);
        final boolean[] result = {false};
        transactionTemplate.execute(transactionStatus ->{
            // 修改question表
            result[0] = questionService.updateById(question);
            ThrowUtils.throwIf(!result[0], ErrorCode.OPERATION_ERROR);
            // 如果旧的标签等于传递的标签，那么直接退出
            if(oldQuestion.getTags().equals(JSONUtil.toJsonStr(questionUpdateRequest.getTags()))){
                return result[0];
            }
            // 修改question_tag表,先删除，在新增
            QueryWrapper<QuestionTag> questionTagQueryWrapper = new QueryWrapper<>();
            questionTagQueryWrapper.eq("questionId",id);
            questionTagService.remove(questionTagQueryWrapper);
            // 新增
            List<QuestionTag> questionTagList = new ArrayList<>();
            List<Integer> tagIds = questionUpdateRequest.getTagIds();
            if(CollUtil.isNotEmpty(tagIds)){
                tagIds.forEach(tag -> {
                    QuestionTag questionTag = new QuestionTag();
                    questionTag.setQuestionId(id);
                    questionTag.setTagId(tag);
                    questionTagList.add(questionTag);
                });
            }
            if(CollUtil.isNotEmpty(questionTagList)){
                boolean b = questionTagService.saveBatch(questionTagList);
                ThrowUtils.throwIf(!b, ErrorCode.OPERATION_ERROR);
            }
            return result[0];
        });
        return ResultUtils.success(result[0]);
    }

    /**
     * 根据 id 获取(脱敏)
     *
     * @param id
     * @return
     */
    @GetMapping("/get/vo")
    public BaseResponse<QuestionVO> getQuestionVOById(long id, HttpServletRequest request) {
        if (id <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        Question question = questionService.getById(id);
        if (question == null) {
            throw new BusinessException(ErrorCode.NOT_FOUND_ERROR);
        }
        return ResultUtils.success(questionService.getQuestionVO(question, request));
    }
    /**
     * 根据 id 获取
     *
     * @param id
     * @return
     */
    @GetMapping("/get")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    public BaseResponse<Question> getQuestionById(long id, HttpServletRequest request) {
        if (id <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        Question question = questionService.getQuestion(id, request);
        return ResultUtils.success(question);
    }

    /**
     * 分页获取列表（仅管理员）
     *
     * @param questionQueryRequest
     * @return
     */
    @PostMapping("/list/page")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    public BaseResponse<Page<Question>> listQuestionByPage(@RequestBody QuestionQueryRequest questionQueryRequest) {
        long current = questionQueryRequest.getCurrent();
        long size = questionQueryRequest.getPageSize();
        Page<Question> questionPage = questionService.page(new Page<>(current, size),
                questionService.getQueryWrapper(questionQueryRequest));
        return ResultUtils.success(questionPage);
    }

    /**
     * 分页获取列表（封装类）
     *
     * @param questionQueryRequest
     * @param request
     * @return
     */
    @PostMapping("/list/page/vo")
    public BaseResponse<Page<QuestionVO>> listQuestionVOByPage(@RequestBody QuestionQueryRequest questionQueryRequest,
            HttpServletRequest request) {
        long current = questionQueryRequest.getCurrent();
        long size = questionQueryRequest.getPageSize();
        // 限制爬虫
        ThrowUtils.throwIf(size > 20, ErrorCode.PARAMS_ERROR);
        Page<Question> questionPage = questionService.page(new Page<>(current, size),
                questionService.getQueryWrapper(questionQueryRequest));
        return ResultUtils.success(questionService.getQuestionVOPage(questionPage, request));
    }

    /**
     * 编辑（用户）
     *
     * @param questionEditRequest
     * @param request
     * @return
     */
    @PostMapping("/edit")
    public BaseResponse<Boolean> editQuestion(@RequestBody QuestionEditRequest questionEditRequest, HttpServletRequest request) {
        if (questionEditRequest == null || questionEditRequest.getId() <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        Question question = new Question();
        BeanUtils.copyProperties(questionEditRequest, question);
        List<String> tags = questionEditRequest.getTags();
        if (tags != null) {
            question.setTags(JSONUtil.toJsonStr(tags));
        }
        JudgeConfig judgeConfig = questionEditRequest.getJudgeConfig();
        if(judgeConfig!=null){
            question.setJudgeConfig(JSONUtil.toJsonStr(judgeConfig));
        }
        List<JudgeCase> judgeCase = questionEditRequest.getJudgeCase();
        if(judgeCase!=null){
            question.setJudgeCase(JSONUtil.toJsonStr(judgeCase));
        }
        // 参数校验
        questionService.validQuestion(question, false);
        User loginUser = userService.getLoginUser(request);
        long id = questionEditRequest.getId();
        // 判断是否存在
        Question oldQuestion = questionService.getById(id);
        ThrowUtils.throwIf(oldQuestion == null, ErrorCode.NOT_FOUND_ERROR);
        // 仅本人或管理员可编辑
        if (!oldQuestion.getUserId().equals(loginUser.getId()) && !userService.isAdmin(loginUser)) {
            throw new BusinessException(ErrorCode.NO_AUTH_ERROR);
        }
        final boolean[] result = {false};
        transactionTemplate.execute(transactionStatus ->{
            // 修改question表
            result[0] = questionService.updateById(question);
            ThrowUtils.throwIf(!result[0], ErrorCode.OPERATION_ERROR);
            // 如果旧的标签等于传递的标签，那么直接退出
            if(oldQuestion.getTags().equals(JSONUtil.toJsonStr(questionEditRequest.getTags()))){
                return result[0];
            }
            // 修改question_tag表,先删除，在新增
            QueryWrapper<QuestionTag> questionTagQueryWrapper = new QueryWrapper<>();
            questionTagQueryWrapper.eq("questionId",id);
            questionTagService.remove(questionTagQueryWrapper);
            // 新增
            List<QuestionTag> questionTagList = new ArrayList<>();
            List<Integer> tagIds = questionEditRequest.getTagIds();
            if(CollUtil.isNotEmpty(tagIds)){
                tagIds.forEach(tag -> {
                    QuestionTag questionTag = new QuestionTag();
                    questionTag.setQuestionId(id);
                    questionTag.setTagId(tag);
                    questionTagList.add(questionTag);
                });
            }
            if(CollUtil.isNotEmpty(questionTagList)){
                boolean b = questionTagService.saveBatch(questionTagList);
                ThrowUtils.throwIf(!b, ErrorCode.OPERATION_ERROR);
            }
            return result[0];
        });
        return ResultUtils.success(result[0]);
    }
    /**
     * 刷题排行榜（前十）
     */
    @GetMapping("/rank")
    public BaseResponse<List<MakeQuestionRankVO>> getMakeQuestionRank(){
        List<MakeQuestionRankVO> makeQuestionRankVOList = questionService.getMakeQuestionRank();
        return ResultUtils.success(makeQuestionRankVOList);
    }
}
